function draggableOnDragStart(e) {
}

function droptargetOnDragEnter(e) {
}

function droptargetOnDragLeave(e) {
}

function droptargetOnDrop(e) {
    var plusOne = e.dropTarget.find('.plusOne');
    plusOne.fadeIn(500).fadeOut(500);
}

function loadTeams() {
    var urlFormat = appBosch.urlGetUsersTeam + '/{0}';
    var containerTeams = $('.container-teams');
    appBosch.teams.forEach(function(team) {
        var code = appBosch.templateTeam(team);
        containerTeams.append(code);
        containerTeams.find('div.team').last().kendoDropTarget({
            dragenter: droptargetOnDragEnter,
            dragleave: droptargetOnDragLeave,
            drop: droptargetOnDrop
        });
    });
    $(document).kendoTooltip({
        filter: '.container-teams div.team',
        content: {
            url: appBosch.urlGetUsersTeam
        },
        width: 400,
        height: 200,
        requestStart: function(e) {
            e.options.url = kendo.format(urlFormat, e.target.data("team-id"));
        }
    });
}

$(document).ready(function() {
    var containerTeams = $('.container-teams');
    $('#addTeam').click(function() {
        $("#loading").show();        
        var vLine = getFirstLine();
        if( vLine ){
            var id = kendo.guid();
            var name = 'Team' + Math.floor(Math.random() * 1000);
            var newTeam = {
                id: id,
                name: name.toUpperCase(),
                area_id: getFirstAreaId(),
                colour_line: '#DDDDDD',
                colour_real: '#DDDDDD',
                line: vLine['text'],
                type: '1',
                shift_id: 1,
                real_line: '',
                colour_virtual_line: '#dddddd',
                colour_real_line: '#dddddd',
                shift: '',
                nomina: '',
                leader: '',
                'line_id' : vLine['value']
            };
            $.getJSON(appBosch.urlCreateGroup,
                    {
                        models: JSON.stringify([newTeam])
                    }, function( data ){
                        newTeam.colour_line = data.colour_line;
                        newTeam.colour_real = data.colour_real;
                        var code = appBosch.templateTeam(newTeam);
                        containerTeams.prepend(code);
                        appBosch.teams.push(newTeam);
                        $("#loading").hide();
                    }).fail(function(){
                        $("#loading").hide();
                    });
            containerTeams.find('div.team').last().kendoDropTarget({
                dragenter: droptargetOnDragEnter,
                dragleave: droptargetOnDragLeave,
                drop: droptargetOnDrop
            });
        }
    });

    $('div.container-teams, div.container-teams-filter').on('click', 'div.team i.destroy', function(e) {
        $('#dlg').html('');
        appBosch.qMessages.msgConfirm = appBosch.msgDestroy;
        appBosch.dlgConfirmTemplate = kendo.template($("#dlgConfirm").html());
        var dlgWindow = $("#dlg").kendoWindow({
            title: "Eliminar equipo",
            modal:true,
            visible: false, //the window will not appear before its .open method is called
            width: 350,
            height: 90
        }).data("kendoWindow");
        dlgWindow.content(appBosch.dlgConfirmTemplate(appBosch.qMessages)); //send the row data object to the template and render it
        dlgWindow.open().center();  
        
        var divTeam = $(this).parents('div.team');

        $("#yesButton").on('click',function(){
            var id = divTeam.data('teamId');
            divTeam.hide();
            $.getJSON(appBosch.urlDestroyGroup, {id: id});
            dlgWindow.close();
        });
        $("#noButton").on('click',function(){
            dlgWindow.close();
        });
        
        e.stopPropagation();
    });
    appBosch.templateAsocLength = kendo.template($('#templateAsocLength').html());
    $('div.container-teams, div.container-teams-filter').on('click', 'div.team i.fa-wrench', function(e) {
        var teamId = $(this).data('teamId');
        var shiftId = $(this).data('shiftId');
        var divTeam = $(this).parents('div.team');
        appBosch.selectedTeam = {
            id: teamId,
            view: divTeam,
            shiftId: shiftId
        };
        var title = $(this).data('teamName');
        $('input#nameTeam').val(title);
        var areaId = divTeam.data('areaId');
        appBosch.currAreaId     = areaId;
        appBosch.currTeamId     = divTeam.data('teamId');
        appBosch.currVLineId    = divTeam.data('teamLineId');
        appBosch.virtualLines   = appBosch.lines[areaId].virtual;
        appBosch.realLines      = appBosch.lines[areaId].real;
        
        loadVirtualLines();
        loadRealLines();
        
        appBosch.wndTeam.title(title).open();
        e.stopPropagation();
    });

    $('div.container-teams').on('click', 'div.team i.fa-credit-card', function(e) {
        e.preventDefault();        
        var divTeam = $(this).parents('div.team');
        appBosch.currAreaId     = divTeam.data('areaId');
        appBosch.currTeamId     = divTeam.data('teamId');
        appBosch.currVLineId    = divTeam.data('teamLineId');
        
        if( appBosch.currVLineId ){//redirect to passports with the line_id and area_id
            $(location).attr('href', appBosch.urlPassport + '?team='+appBosch.currTeamId+'&lineId='+appBosch.currVLineId+'&areaId='+appBosch.currAreaId);
        }
        e.stopPropagation();
    });

    $('div.container-teams').on('click', 'div.team i.fa-dashboard', function (e) {
        e.preventDefault();
        var divTeam = $(this).parents('div.team');
        var teamId = divTeam.data('teamId');
        var url = [appBosch.urlDash, teamId].join('/');
        $(location).attr('href', url);
        e.stopPropagation();
    });

    $('div.container-teams, div.container-teams-filter').on('click', 'div.team', function() {
        var divTeam = $(this);
        var teamId     = divTeam.data('teamId');
        var lineId    = divTeam.data('teamLineId');
        if( lineId ) {
            var url = [appBosch.urlMh, lineId, teamId, 0].join('/');
            window.open(url, '_mh');
        }
    });

    $('#addUsers').click(function() {
        $("#loading").show();        
        var url = [appBosch.urlTeamUsersMultiple, appBosch.selectedTeam.id].join('/');
        var nominas = $('#addByNomina').val();
        if( nominas ){
            var validNominas    = [];
            var userErrors      = [];
            var arrayNominas    = nominas.split(' ');
            arrayNominas.forEach(function(nomina){
                if( !existTeamUserByNomina(nomina) ){
                    validNominas.push(nomina);
                }else{
                    userErrors.push({
                        'nomina':nomina,
                        'ec':'03'
                    });
                }
            });
            if( validNominas.length > 50 ){
                validNominas = validNominas.splice( 49, Number.MAX_VALUE );
            }
            if( validNominas.length ){
                $.getJSON(url, {
                    u: validNominas.join(' ')
                }, function(c) {
                    var urlTeamUsers = [appBosch.urlActiveTeamUsers, appBosch.selectedTeam.id].join('/');
                    loadTeamUsers(urlTeamUsers);

                    var errorUsers = c.errors !== undefined ? c.errors : [];
                    errorUsers.forEach(function(errorUser) {
                        userErrors.push({
                            'nomina':errorUser.nomina,
                            'ec':errorUser.rc
                        });
                    });
                    if( userErrors.length >= 1 ){
                        showDlgAddUsers(userErrors, validNominas.length - errorUsers.length );
                    }
                    $('#addByNomina').val('');
                    $("#loading").hide();
                }).fail(function() {
                    $('#addByNomina').val('');
                    $("#loading").hide();
                });
            }else{
                $("#loading").hide();
                showDlgAddUsers( userErrors, 0 );
            }
        }else{
            $("#loading").hide();
        }
    });

    $('#deleteUsers').click(function() {
        $("#loading").show();
        var url = [appBosch.urlDelTeamUsersMultiple, appBosch.selectedTeam.id].join('/');
        var nominas = $('#deleteByNomina').val();
        if( nominas ) {
            var validNominas    = [];
            var userErrors      = [];
            var arrayNominas    = nominas.split(' ');
            arrayNominas.forEach(function(nomina){
                if( existTeamUserByNomina(nomina) ){
                    validNominas.push(nomina);
                }else{
                    userErrors.push({
                        'nomina':nomina,
                        'ec':'04'
                    });
                }
            });
            if( validNominas.length > 50 ){
                validNominas = validNominas.splice( 49, Number.MAX_VALUE );
            }
            if( validNominas.length ){
                $.getJSON(url, {
                    u: validNominas.join(' ')
                }, function(c) {
                    var urlTeamUsers = [appBosch.urlActiveTeamUsers, appBosch.selectedTeam.id].join('/');
                    loadTeamUsers(urlTeamUsers);

                    var errorUsers = c.errors !== undefined ? c.errors : [];
                    errorUsers.forEach(function(errorUser) {
                        userErrors.push({
                            'nomina':errorUser.nomina,
                            'ec':errorUser.rc
                        });
                    });
                    if( userErrors.length >= 1 ){
                        showDlgDelUsers(userErrors, validNominas.length - errorUsers.length );
                    }
                    $('#addByNomina').val('');
                    $("#loading").hide();
                }).fail(function() {
                    $('#addByNomina').val('');
                    $("#loading").hide();
                });
            }else{
                $("#loading").hide();
                showDlgDelUsers( userErrors, 0 );
            }
        }else{
            $("#loading").hide();
        }
    });
    
    $('#cleanTeam').on('click',function(){
        $('#dlg').html('');
        appBosch.qMessages.msgConfirm = appBosch.msgCleanTeam;
        appBosch.dlgConfirmTemplate = kendo.template($("#dlgConfirm").html());
        var dlgWindow = $("#dlg").kendoWindow({
            title: "Limpiar equipo",
            modal:true,
            visible: false, //the window will not appear before its .open method is called
            width: 350,
            height: 90
        }).data("kendoWindow");
        dlgWindow.content(appBosch.dlgConfirmTemplate(appBosch.qMessages)); //send the row data object to the template and render it
        dlgWindow.open().center();  

        $("#yesButton").on('click',function(){
            $.get(appBosch.urlCleanTeam,{'teamId':appBosch.currTeamId},function(data){
                if( data.deleted ){
                    appBosch.myTeamUsers = [];
                    appBosch.myTeamLines = [];
                    $('.container-users .my').html('');
                    $('.container-lines .my').html('');   
                }
            });
            dlgWindow.close();
        });
        $("#noButton").on('click',function(){
            dlgWindow.close();
        });
        
        e.stopPropagation();
    });
});

function showDlgAddUsers( userErrors, added ){
    var msg  = appBosch.qMessages.msgAddedUsers;
    var msg2 = '';
    if( userErrors.length ) {
        msg2 = appBosch.qMessages.msgAddedUsersError;
    }
    msg = msg.replace( 'XX', added );
    msg += ' ' + msg2;
    showDlgInsertErrors( {
        'msg': msg,
        'userErrors' : userErrors
    } );
}

function showDlgDelUsers( userErrors, deleted ){
    var msg  = appBosch.qMessages.msgDeletedUsers;
    var msg2 = '';
    if( userErrors.length ) {
        msg2 = appBosch.qMessages.msgDeletedUsersError;
    }
    msg = msg.replace( 'XX', deleted );
    msg += ' ' + msg2;
    showDlgInsertErrors( {
        'msg': msg,
        'userErrors' : userErrors
    } );
}

function getFirstAreaId(){
    return appBosch.areas.length ? appBosch.areas[0].area_id : '';
}

function getFirstLine(){
    var line = false;
    
    if( appBosch.lines ){
        var virtualLines = appBosch.lines[getFirstAreaId()].virtual;
        if(virtualLines){
            line = virtualLines[0];
        }
    }
    return line;
}
